package com.aispeech.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

@Slf4j
public final class RestfulClient {
    public static void main(String[] args) {
        JSONObject version = getAsJSONObject("http://localhost:2379/v2/keys");
        log.info(version.toJSONString());
    }

    private static JSONObject execute(HttpUriRequest request) {
        JSONObject result = null;

        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            CloseableHttpResponse resp = httpClient.execute(request);

            if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = resp.getEntity();

                if (entity != null) {
                    BufferedReader reader;
                    reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 10 * 1024);
                    StringBuilder strBuilder = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        strBuilder.append(line);
                    }

                    result = JSON.parseObject(strBuilder.toString());
                } else {
                    log.error("http entity is null");
                }
            } else {
                log.error("{}", resp.getStatusLine());
            }
        } catch (Exception e) {
            log.error(request.toString(), e);
        }

        return result;
    }

    public static JSONObject getAsJSONObject(String url) {
        HttpGet get = new HttpGet(url);
        return execute(get);
    }

    public static JSONObject multipart(String url, JSONObject params, String filePath) {
        HttpPost post = new HttpPost(url);
        post.setEntity(MultipartEntityBuilder.create()
                .addPart("file", new FileBody(new File(filePath)))
                .addTextBody("params", params.toJSONString())
                .build());

        return execute(post);
    }
}
